package me.guyongquan.cal10npropwriter;

import java.util.HashMap;
import java.util.Map;

import me.guyongquan.cal10npropwriter.annotation.PropCharset;
import me.guyongquan.cal10npropwriter.annotation.PropCharsets;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SingleMemberAnnotation;
import org.eclipse.jdt.core.dom.StringLiteral;

public class GetCharsetVisitor extends ASTVisitor{
	public Map<String, String> charsets = new HashMap<String, String>();
	public boolean  visit(NormalAnnotation annotation) {
		if(PropCharset.class.getName().endsWith(annotation.getTypeName().getFullyQualifiedName())) {
			PropCharsetVisitor visitor = new PropCharsetVisitor();
			annotation.accept(visitor);
			String locale = visitor.map.get("locale");
			String charset = visitor.map.get("charset");
			charsets.put(locale, charset);
		}
		return true;
	}
	private static class PropCharsetVisitor extends ASTVisitor {
		Map<String, String> map = new HashMap<String, String>();
		@Override
		public boolean visit(MemberValuePair node) {
			String name = node.getName().getFullyQualifiedName();
			MemberValueVisitor visitor = new MemberValueVisitor();
			node.getValue().accept(visitor);
			map.put(name, visitor.value);
			return true;
		}
	}
	
	private static class MemberValueVisitor extends ASTVisitor {
		String value;
		@Override
		public boolean visit(StringLiteral node) {
			value = node.getLiteralValue();
			return true;
		}
		
		@Override
		public void postVisit(ASTNode node) {
			if (value == null) {
				node.accept(new ASTVisitor() {
					@Override
					public boolean visit(QualifiedName node) {
						throw new UnsupportedOperationException(node.getFullyQualifiedName());
					}
				});
			}
		}
	}
}
